// import Cookie from 'js-cookie'
import { removeAuthorization } from '@/utils/request'

// import {
//   LOGIN,
//   LOGIN_VERIFI_CODE,
//   LOGIN_SEND_MSG,
//   LOGIN_CHECK_CODE,
//   LOGIN_FORGOT,
//   FIRST_LOGIN_SENDMSG
// } from '@/services/api'

const respCommon = {
  onFulfilled (response, options) {
    // const { message, router } = options
    const { router } = options
    const { status, data } = response
    // 服务器返回登录token失效
    if (status === 200 &&
        Object.hasOwnProperty.call(data, 'code') &&
        data.code === 401) {
      removeAuthorization()
      // message.error('认证 token 已过期，请重新登录')
      router.push('/login')
    }
    if (response.status === 500) {
      return { isSuccess: false, msg: '500: 服务器内部错误', data: null }
    }
    if (response.status === 502) {
      return { isSuccess: false, msg: '502: 网关异常', data: null }
    }
    if (response.status === 403) {
      return { isSuccess: false, msg: '403: 请求被拒绝', data: null }
    }
    if (response.status === 401) {
      removeAuthorization()
      router.push('/login')
      return { isSuccess: false, msg: '401: 无此权限', data: null }
    }
    if (response.status !== 200 && response.data) {
      if (response.data?.msg) {
        return { isSuccess: false, msg: `${response.status}: ${response.data.msg}`, data: null }
      } else return { isSuccess: false, msg: 'error', data: null }
    }
    if (response.status === 200 && response.data === '网关异常') {
      return { isSuccess: false, msg: '502: 网关异常', data: null }
    }
    return response.data || { isSuccess: false, msg: 'error', data: null }
  }
}

const reqCommon = {
  /**
   * 发送请求之前做些什么
   * @param config axios config
   * @param options 应用配置 包含: {router, i18n, store, message}
   * @returns {*}
   */
  onFulfilled (config, options) {
    // config.responseType = 'blob'
    // console.log(config)
    // const { message } = options
    // const { url, xsrfCookieName } = config
    // const ignoreList = [
    //   LOGIN,
    //   LOGIN_VERIFI_CODE,
    //   LOGIN_SEND_MSG,
    //   LOGIN_CHECK_CODE,
    //   LOGIN_FORGOT,
    //   FIRST_LOGIN_SENDMSG
    // ]
    // console.log('reqCommon', config)
    // if (!ignoreList.find(d => url.indexOf(d) >= 0) && xsrfCookieName && !Cookie.get(xsrfCookieName)) {
    //   message.warning('认证 token 已过期，请重新登录')
    // }
    return config
  },
  /**
   * 请求出错时做点什么
   * @param error 错误对象
   * @param options 应用配置 包含: {router, i18n, store, message}
   * @returns {Promise<never>}
   */
  onRejected (error, options) {
    const { message } = options
    message.error(error.message)
    return Promise.reject(error)
  }
}

export default {
  request: [reqCommon], // 请求拦截
  response: [respCommon] // 响应拦截
}
